import axios from "axios";
import React, { useEffect, useState } from "react";
import PubSub from "pubsub-js";
import { Link, useNavigate } from "react-router-dom";

export default function HeroList() {
  //声明状态
  let [heros, setHeros] = useState([]);
  //定义一个状态
  let [keyword, setKeyword] = useState("");
  //声明一个状态
  let [isFirst, setIsFirst] = useState(true);
  //声明状态 是否正在请求中..
  let [isLoading, setIsLoading] = useState(false);

  //组件挂载完毕的操作
  useEffect(() => {
    let getHeros = async () => {
      //判断 如果是第一次, 就不发请求
      if (isFirst) return;
      //修改状态为请求中...
      setIsLoading(true);
      //清空英雄数组
      setHeros([]);
      //发送请求
      let result = await axios.get("http://api.xiaohigh.com/heros", {
        params: {
          name_like: keyword,
        },
      });
      //更新状态
      setHeros(result.data);
      //修改状态不在请求中..
      setIsLoading(false);
    };
    getHeros();
  }, [keyword, isFirst]);

  useEffect(() => {
    //订阅
    PubSub.subscribe("hero_keyword", (channel, data) => {
      setKeyword(data);
      //将第一次的状态改为false
      setIsFirst(false);
    });
    //组件销毁时, 取消订阅
    return () => {
      PubSub.unsubscribe("hero_keyword");
    };
  }, []);

  //获得 navigate 函数
  let navigate = useNavigate();

  return (
    <div className="hero-list">
      {heros.map((item) => {
        return (
          <div className="hero-item" key={item.id}>
            <img onClick={() => {
              //跳转
              navigate(`/hero`, {
                state: {
                  id: item.id
                },
                //是否为替换模式
                // replace: true
              });
            }} src={"http://cdn.xiaohigh.com" + item.image} alt="" />
            <p>{item.name}</p>
          </div>
        );
      })}
      {/* 是否为第一次 */}
      {isFirst && <h2 style={{ textAlign: "center" }}>欢迎来到王者荣耀</h2>}
      {/* 是否结果为空 */}
      {!isLoading && heros.length === 0 && !isFirst && <h2 style={{ textAlign: "center" }}>暂无数据</h2>}
      {/* 是否正在加载中... */}
      {isLoading && <h2 style={{ textAlign: "center" }}>加载中....</h2>}
    </div>
  );
}
